<?php

require_once 'dbutils.php';
require_once 'RestUtils.php';
require_once 'Base.php';

class WishJourneys extends Base
{

    function GET($matches)
    {
        $req = RestUtils::processRequest('GET');
        $req_vars = $req->getRequestVars();
        $db_vars = dbutils::translate_rest_params($req_vars);
        $res = $this->selectWishJourneys($db_vars);
        if ($res['code'] == 0)
            RestUtils::sendResponse(200, $res['result'], 'application/json');
        else
            RestUtils::sendResponse(404, dbutils::error_to_json($res['code'], $res['message']), 'application/json');
    }

    private function selectWishJourneys($values)
    {
        $code = 0;
        $msg = '';
        $result = null;
        try {
            if (!$values)
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);

            if (!array_key_exists('departure_lat', $values)
                || !array_key_exists('departure_lng', $values)
                || !array_key_exists('arriva_lat', $values)
                || !array_key_exists('arriva_lng', $values)
                || !array_key_exists('departure_datetime', $values)
                || !array_key_exists('metersTolerance', $values)
                || !array_key_exists('timeTolerance', $values)
            )
                return array('code' => -1, 'message' => 'required request parameters not found', 'result' => null);


            $earth_radius = 6371000;
            $rad_dist_tol = $values['metersTolerance'] / $earth_radius;
            $cos_rad_dist_tol = cos($rad_dist_tol);

            $diff_lat = rad2deg($rad_dist_tol);
            $departure_lat1 = $values['departure_lat'] - $diff_lat;
            $departure_lat2 = $values['departure_lat'] + $diff_lat;

            $diff_lng = rad2deg(acos(1 + ($cos_rad_dist_tol - 1) * (1 + pow(tan(deg2rad($values['departure_lat'])), 2))));
            $departure_lng1 = $values['departure_lng'] - $diff_lng;
            $departure_lng2 = $values['departure_lng'] + $diff_lng;

            $arriva_lat1 = $values['arriva_lat'] - $diff_lat;
            $arriva_lat2 = $values['arriva_lat'] + $diff_lat;

            $diff_lng = rad2deg(acos(1 + ($cos_rad_dist_tol - 1) * (1 + pow(tan(deg2rad($values['arriva_lat'])), 2))));
            $arriva_lng1 = $values['arriva_lng'] - $diff_lng;
            $arriva_lng2 = $values['arriva_lng'] + $diff_lng;

            $time_tolerance = new DateInterval('PT' . str_replace(':', 'H', $values['timeTolerance']) . 'M');
            $departure_datetime1 = new DateTime($values['departure_datetime']);
            $departure_datetime2 = new DateTime($values['departure_datetime']);
            $departure_datetime2->add($time_tolerance);
            $departure_datetime1->sub($time_tolerance);
            $departure_datetime2 = $departure_datetime2->format('Y-m-d H:i:s');
            $departure_datetime1 = $departure_datetime1->format('Y-m-d H:i:s');

            $query = "SELECT uj.id_user, j.id AS id_journey,
                             to_char(j.departure_datetime, 'YYYY-MM-DD HH24:MI') AS departure_datetime,
                             j.passengers, j.luggages, r.departure_lat,
                             r.departure_lng, r.arriva_lat,
                             r.arriva_lng, r.route_lenght_mt,
                             r.departure_addr, r.arriva_addr
                      FROM journeys j, routes r, user_journeys uj
                      WHERE j.id_route = r.id
                      AND uj.id_journey = j.id
                      AND r.departure_lat BETWEEN {$departure_lat1} AND {$departure_lat2}
                      AND r.departure_lng BETWEEN {$departure_lng1} AND {$departure_lng2}
                      AND r.arriva_lat BETWEEN {$arriva_lat1} AND {$arriva_lat2}
                      AND r.arriva_lng BETWEEN {$arriva_lng1} AND {$arriva_lng2}
                      AND TIMESTAMP '{$departure_datetime1}' <= j.departure_datetime
                      AND j.departure_datetime <= TIMESTAMP '{$departure_datetime2}'
                      AND j.status = 'OPEN'";

            $db_handle = @pg_pconnect(dbutils::$conn_string);
            $result = @pg_query($db_handle, $query);
            if ($result) {
                $result = dbutils::dbresult_to_json($result);
            }
            else {
                $code = -1;
                $msg = 'no db records found ' . @pg_last_error($db_handle);
            }
            @pg_close($db_handle);

        } catch (Exception $e) {
            $code = $e->getCode();
            $msg = $e->getMessage();
        }

        return array('code' => $code, 'message' => $msg, 'result' => $result);
    }
}

?>